using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
using ConfigManager.Core.Instructions;

namespace ConfigManager.Core
{
    public class XmlConfigGenerator
    {
        private IDictionary<string, string> _properties = new Dictionary<string, string>();

        /// <summary>
        /// Gets or sets the properties dictionary.
        /// </summary>
        /// <value>The properties dictionary.</value>
        public IDictionary<string, string> PropertiesDictionary
        {
            get { return _properties; }
            set { _properties = value; }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="XmlConfigGenerator"/> class.
        /// </summary>
        public XmlConfigGenerator()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="XmlConfigGenerator"/> class.
        /// </summary>
        /// <param name="properties">The properties.</param>
        public XmlConfigGenerator(IDictionary<string, string> properties)
        {
            _properties = properties;
        }

        /// <summary>
        /// Generates the configuration.
        /// </summary>
        /// <param name="template">The template.</param>
        /// <returns></returns>
        public string GenerateConfiguration(string template)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(template);

            XmlInstruction[] instructions = XmlInstructionParser.Parse(xmlDoc, _properties);
            foreach (XmlInstruction inst in instructions)
                inst.Run();

            MemoryStream memStream = new MemoryStream();
            XmlTextWriter xw = new XmlTextWriter(memStream, Encoding.UTF8);
            xw.Formatting = Formatting.Indented;
            xmlDoc.WriteTo(xw);

            xw.Flush();
            memStream.Flush();

            return System.Text.Encoding.UTF8.GetString(memStream.ToArray());
        }
    }
}
